import { lazy } from 'react'
import { routers } from './routes';
import { layoutLoader } from './root';
import { KeepAlive } from 'react-keep-alive'
import type { CustomRouteObject } from './types';

const Login = lazy(() => import('@/pages/Login'));
const MainLayout = lazy(() => import('@/layout'));
const Error = lazy(() => import('@/pages/ExceptionPages/Error'));
const NotFound = lazy(() => import('@/pages/ExceptionPages/NotFound'));

export const routes: CustomRouteObject[] = [
  {
    path: '/',
    element: <MainLayout />,
    errorElement: <Error />,
    children: keepAliveFnc(routers),
    loader: layoutLoader
  },
  {
    path: 'login',
    element: <Login />
  },
  {
    path: '*',
    element: <NotFound />
  }
]

export function keepAliveFnc(routes: CustomRouteObject[]) {
  for (let i=0; i<routers.length; i++) {
    const route = routes[i];
    if (route.element) {
      route.element = (
        <KeepAlive name={route.path}>
          { route.element }
        </KeepAlive>
      )
    }
  }
  return routes
}

export {
  routers
}